﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Represents a friend domain object.  A friend list may be retrieved from this. A friend list is saved as a text file.
/// 
/// NOTE: somewhere, we need a list of all SocialKlee users.  SQL Server might natively support this. 
/// </summary>
public class Friend
{
    private FriendDatabaseAdapter adapter;

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public static string WebDirectory { get; set; }

    public List<Friend> FriendList {get; set;}

    private string friendListFile;

    private const char DELIMETER = ',';
       
	public Friend()
	{
        this.FriendList = new List<Friend>();
        this.adapter = new FriendDatabaseAdapter();
	}

    /// <summary>
    /// 
    /// </summary>
    /// <param name="firstName"></param>
    /// <param name="lastName"></param>
    /// <param name="UserName"></param>
    /// <param name="email"></param>
    /// <remarks>
    /// In case it isn't obvious, the call to this() will initialize this.FriendList and this.adapter.
    /// </remarks>
    public Friend(string firstName, string lastName, string UserName, string email) : this()
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.UserName = UserName;
        this.friendListFile = string.Format("{0}\\{1}-friend-list.txt", WebDirectory, UserName);
        this.Email = email;
        
    }

    public bool hasFriendListFile()
    {
        bool exists = File.Exists(friendListFile);
        return exists;
    }

    /// <summary>
    /// Returns a list of people the friend may know.
    /// </summary>
    /// <returns></returns>
    public List<Friend> GetPossibleFriends(int numberOfFriends)
    {
        List<Friend> possibleFriends = new List<Friend>();
        Random random = new Random(numberOfFriends);

        for (int i = 0; i < numberOfFriends; i++)
            possibleFriends.Add(FriendList[random.Next()]);

        return possibleFriends;
    }

    /// <summary>
    /// Create a friend list text file
    /// </summary>
    public void CreateFriendListFile()
    {
        StreamWriter writer;
        try
        {
            using (writer = new StreamWriter(this.friendListFile))
                foreach (Friend friend in this.FriendList)
                    WriteFriendEntry(writer, friend);
        }
        catch (Exception ex)
        {

        }
    }

    /// <summary>
    /// Create a friend list text file
    /// </summary>
    /// <param name="friendList"></param>
    public void CreateFriendListFile(List<Friend> friendList)
    {
        StreamWriter writer;
        try
        {
            using (writer = new StreamWriter(this.friendListFile))
                foreach (Friend friend in friendList)
                    WriteFriendEntry(writer, friend);
        }
        catch (Exception ex)
        {

        }
    }

    private void WriteFriendEntry(StreamWriter writer, Friend aFriend)
    {
        writer.WriteLine(aFriend.ToString());
    }

    /// <summary>
    /// Add a friend to the friendlist text file
    /// </summary>
    /// <param name="aFriend"></param>
    public void AddFriendEntryToFile(Friend aFriend)
    {
        try
        {
            List<Friend> friendList = GetFriendListFromFile(this.friendListFile);
            friendList.Add(aFriend);
            File.Delete(this.friendListFile);   // remove friend list file
            CreateFriendListFile(friendList);   // recreate file

        }
        catch (Exception ex) { }

    }

    public List<Friend> GetFriendListFromFile()
    {
        List<Friend> friendList = new List<Friend>();
        StreamReader reader;

        using (reader = new StreamReader(this.friendListFile))
        {
            while (!reader.EndOfStream)
            {
                string[] item = reader.ReadLine().Split(DELIMETER);
                friendList.Add(new Friend(item[0], item[1], item[2], item[3]));
            }
        }

        return friendList;
    }

    public Friend SplitFriendTextToObject(string friendText)
    {
        string[] text = friendText.Split(DELIMETER);
        return new Friend(text[0], text[1], text[2], text[3]); 
    }

    public List<Friend> GetFriendListFromFile(string friendListFile)
    {
        List<Friend> friendList = new List<Friend>();
        StreamReader reader;

        using (reader = new StreamReader(friendListFile))
        {
            while (!reader.EndOfStream)
            {
                string[] item = reader.ReadLine().Split(DELIMETER);
                friendList.Add(new Friend(item[0], item[1], item[2], item[3]));
            }
        }

        return friendList;
    }

    public List<Friend> GetAllFriends()
    {
        List<Friend> allFriends = new List<Friend>();
        try
        {
            this.adapter.Open();
            if (adapter.DoesTableExist(FriendDatabaseAdapter.REGISTRATION_TABLE))
            {
                allFriends = adapter.GetAllFriends();
            }

        }
        catch (Exception ex) { }
        finally { this.adapter.Close(); }

        return allFriends;
    }

    /// <summary>
    /// Display friend's first name, last name, user id, and email
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return string.Format("{0},{1},{2},{3}", this.FirstName, this.LastName, this.UserName, this.Email);
    }

    /// <summary>
    /// Returns only user id.
    /// </summary>
    /// <param name="isIdOnly"></param>
    /// <returns></returns>
    public string ToString(bool isIdOnly)
    {
        return this.UserName;
    }
}